<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- table -->
      <BreakSpace label="旧件交接信息" :containerStyle="{ marginBottom: '10px' }" />
      <FormPanel ref="formPanel" :list="formList" :cols="4" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
      <BreakSpace label="上传视频/压缩文件" :containerStyle="{ marginBottom: '10px' }" />
      <Spin :spinning="loading" tip="Loading...">
        <UploadFile action-url="/api/file/oss/upload"  :fileTypes="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'rar', 'zip','mp4','avi','rmvb','WMV','ins','inr']" :fileSize="100" :isOnlyButton="true"  :limit="10000" @change="successHandler">上传附件</UploadFile>
        <FilterTable
          ref="fileTable"
          :columns="columnsFile"
          columnsRef="whbydUploadFile"
          :isSelectColumn="false"
          :onColumnsChange="columnsFile => (this.columnsFile = columnsFile)"
          height=auto
          :dataSource="list"
        />
      </Spin>
      <div style="padding-top: 3rem"></div>
      <div
        :style="{
          position: 'fixed',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }"
      >
        <multiuse-button type="primary" :click="apply.bind()">上 传</multiuse-button>
        <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
        <multiuse-button @click="closeDialog">关 闭</multiuse-button>
      </div>
    </div>
  </Spin>
</template>
<script>
import { updateByPtId, applyDestory } from '@/api/usedPartsDestructionDealer/usedPartsHandover';
import { getPartType } from '@/api/dictionary';
//手机号校验
import { phone } from '@/utils/validate';
import moment from "moment";

export default {
  props: ['editRow'],
  // mixins: [dictionary],
  data() {
    return {
      loading: false,
      dataList: [],
      dataList1: [],
      visible: false,
      visibleDrawer: false,
      collapse: false,
      infoId: null,
      flterValue: {}, //参数
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      saveData: null,
      activeName: '审核记录',
      saveDataFile: {},
      visibleList: false,
      columnsFile: this.createdTable(),
      list: [],
    };
  },
  async created() {
    this.loading = true;
    await this.assignment();
    this.loading = false;
  },
  mounted() {
    this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(this.editRow.fileList || []);
  },
  methods: {
    async assignment() {
      let res = await getPartType({ type: 5531 });
      for (let row in this.editRow) {
        this.formList.map(x => {
          if (this.editRow.fileList != null) {
            // if (row == 'fileList' && x.fieldName == 'wayFiles') {
            //   x.initialValue = this.editRow.fileList.map(f => ({ name: f.title, url: f.fileUrl }));
            // }
          }
          if (x.fieldName == 'destoryStatus') {
            x.initialValue = res.data.find(x => x.codeId == this.editRow.destoryStatus).codeCnDesc;
          }
          if (x.fieldName == row) {
            x.initialValue = this.editRow[row];
          }
        });
      }
    },
    delVideo(val){
      console.log("#@!#!",val)
      this.$refs.fileTable.$refs.pageTable.EXECUTE_DELETE([val]);
    },
    // 上传成功回调
    successHandler(val) {
      if(val == 1){
        this.loading = true;
      }else{
        this.loading = false;
        if (val&&val.length>0) {
          if (val[0].url.errorList&&val[0].url.errorList.length>0) {
            this.errorList = val[0].url.errorList;
          }else{
            let json = JSON.parse(JSON.stringify(val));
            let data = {};
            data.createdAt = moment().format('YYYY-MM-DD HH:mm:ss');
            data.title = json[json.length - 1].name;
            data.fileUrl = json[json.length - 1].url;
            this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(data);
          }
        }else{
          this.errorList = []
        }
      }
    },
    onCellChange(columns, row) {
      let sum = 0;
      this.$refs.table.$refs.pageTable.list.map(x => {
        console.log(x);
        sum += Number(x.pestructionCount);
      });
      this.formList.find(x => x.fieldName == 'destoryCount').initialValue = sum;
      this.formList.find(x => x.fieldName == 'cmsClaimCount').initialValue = this.$refs.table.$refs.pageTable.list.length;
    },
    add() {
      this.visibleList = true;
    },
    closeAdd() {
      this.visibleList = false;
    },
    saveAdd(val) {
      this.visibleList = false;
      let list = Object.assign([], val);
      let pageList = this.$refs.table.$refs.pageTable.list;
      val.map(x => {
        if (pageList.find(f => f.claimId != x.claimId)) {
          list.push(x);
        }
      });
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE(this.$refs.table.$refs.pageTable.list);
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(list);
      this.formList.find(x => x.fieldName == 'cmsClaimCount').initialValue = this.$refs.table.$refs.pageTable.list.length;
      let num = 0;
      this.$refs.table.$refs.pageTable.list.map(x => {
        num += Number(x.pestructionCount || 0);
      });
      this.formList.find(x => x.fieldName == 'destoryCount').initialValue = num;
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    formChangeHandleFile(val) {
      this.saveDataFile = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    deleteHandle(row) {
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([row]);
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let fileList = [];
      if (this.saveData) {
        let save = Object.assign({}, this.saveData);
        this.$refs.fileTable.$refs.pageTable.list.map(x => {
          delete x.fileId
          fileList.push(x);
        });
        save.fileList = fileList;
        save.dtlStatus = 55311010;

        for (let a in this.editRow) {
          if (save[a]) {
            this.editRow[a] = save[a];
          }
        }
        console.log(this.editRow);
        this.loading = true;
        let res = await updateByPtId(this.editRow);
        if (res.resultCode == 200) {
          this.$emit('save');
        } else {
          this.loading = false;
        }
        this.loading = false;
      }
    },
    async apply() {
      this.$refs.formPanel.SUBMIT_FORM();
      let fileList = [];
      if (this.saveData) {
        let save = Object.assign({}, this.saveData);
        this.$refs.fileTable.$refs.pageTable.list.map(x => {
          delete x.fileId
          fileList.push(x);
        });
        save.fileList = fileList;
        save.dtlStatus = 55311011;

        for (let a in this.editRow) {
          if (save[a]) {
            this.editRow[a] = save[a];
          }
        }
        console.log(this.editRow);
        this.loading = true;
        let res = await updateByPtId(this.editRow);
        if (res.resultCode == 200) {
          this.$emit('save');
        } else {
          this.loading = false;
        }
        this.loading = false;
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close');
    },
    chooseOrderNo() {
      this.visible = true;
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '索赔单号',
          fieldName: 'cmsClaimNo',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '旧件代码',
          fieldName: 'partCode',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '旧件名称',
          fieldName: 'partName',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '主损件代码',
          fieldName: 'mainPartCode',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '主损件名称',
          fieldName: 'mainPartName',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'supName',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '索赔单类型',
          fieldName: 'cmsClaimTypeStr',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelName',
          placeholder: '',
          readonly: true,
          disabled: true,
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '交接人',
          fieldName: 'hdBy',
          placeholder: '请输入交接人',
          rules: [{ required: true, message: '请输入交接人', trigger: 'blur' }],
          initialValue: ''
        },
        {
          type: 'DATE',
          label: '交接时间',
          fieldName: 'hdDate',
          placeholder: '请选择日期',
          valueFormat: 'yyyy-MM-dd', //返回数据格式
          rules: [{ required: true, message: '请选择日期', trigger: 'blur' }],
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '物流名称',
          fieldName: 'expressName',
          placeholder: '请输入物流名称',
          rules: [{ required: true, message: '请输入物流名称', trigger: 'blur' }],
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '物流电话',
          fieldName: 'expressTel',
          placeholder: '请输入物流电话',
          rules: [{ required: true, message: '请输入物流电话', validator: phone, trigger: 'blur' }],
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '接收人',
          fieldName: 'colBy',
          placeholder: '请输入接收人',
          rules: [{ required: true, message: '请输入接收人', trigger: 'blur' }],
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '接收人电话',
          fieldName: 'colTel',
          placeholder: '请输入接收人电话',
          rules: [{ required: true, message: '请输入接收人电话', validator: phone, trigger: 'blur' }],
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '接收地址',
          fieldName: 'colAddress',
          placeholder: '请输入接收地址',
          rules: [{ required: true, message: '请输入接收地址', trigger: 'blur' }],
          initialValue: '',
          selfCols: 4 // 元素占据几行
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'hdRemarks',
          placeholder: '请输入备注',
          rows: 3,
          selfCols: 4, // 元素占据几行
          initialValue: ''
        },
        // {
        //   type: 'UPLOAD_FILE',
        //   label: '上传附件',
        //   fieldName: 'wayFiles',
        //   placeholder: '上传附件...',
        //   initialValue: [],
        //   rules: [{ required: true, message: '请上传文件', trigger: 'change' }],
        //   upload: {
        //     actionUrl: '/api/file/oss/upload',
        //     limit: 30,
        //     max: 102400, //kb
        //     tipText: '支持PDF、RAR、JPG格式'
        //   }
        // }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 90,
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delVideo(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '附件标题',
          dataIndex: 'title',
          showOverflowTooltip: true,
          render: p => {
            return (
              <a style="color:#bb0a30" href={p.row.fileUrl} target="_blank" download={p.row.title}>
                {p.row.title}
              </a>
            );
          }
        },
      ];
    },
  }
};
</script>

<style lang="less" scoped></style>
